<template>
  <div class="chat-layout">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h2>聊天记录</h2>
        <el-button type="primary" @click="createNewChat">+ 新对话</el-button>
      </div>
      <div class="chat-list">
        <div
          v-for="(chat, index) in chatList"
          :key="chat"
          class="chat-item"
          :class="{ active: currentChat === chat }"
          @click="switchChat(chat)"
        >
          <el-icon><ChatLineRound /></el-icon>
          <span>对话 {{ index + 1 }}</span>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-container">
      <!-- 聊天记录区域 -->
      <div class="chat-history" ref="chatHistoryRef">
        <div v-for="(message, index) in currentChatMessages" :key="index" class="message-wrapper">
          <!-- 用户消息 -->
          <div v-if="message.role === 'user'" class="message-row user-message">
            <div class="avatar">
              <el-avatar :size="32" :icon="UserFilled" />
            </div>
            <div class="message-content">
              <div class="message-text">{{ message.content }}</div>
            </div>
          </div>
          <!-- AI消息 -->
          <div v-else class="message-row ai-message">
            <div class="avatar">
              <el-avatar :size="32" :icon="Service" />
            </div>
            <div class="message-content">
              <div class="message-text" v-html="message.content"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入消息..."
          @keyup.enter.native.exact="handleSend"
        />
        <div class="button-group">
          <el-button type="primary" @click="handleSend" :loading="loading">
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { UserFilled, Service, ChatLineRound } from '@element-plus/icons-vue'
import { listSessionByUser, listMessageByChatId, chatMessage } from '@/api/ai/knowledge'
import { v4 as uuidv4 } from 'uuid';
import { getToken } from '@/utils/auth'

// 聊天列表数据
const chatList = ref([])

const chatType = ref('knowledge')

const getChatList = async () => {
  // 从本地存储中获取聊天列表数据
  const res = await listSessionByUser(chatType.value)
  chatList.value = res.data
  currentChat.value = chatList.value[0]
  switchChat(currentChat.value)
}

// 当前选中的聊天ID
const currentChat = ref()

const isStreaming = ref(false)

// 当前聊天的消息列表
const currentChatMessages = ref([])

// 获取当前聊天的消息列表
const getChatMessages = async (chatId) => {
  const res = await listMessageByChatId(chatId)
  currentChatMessages.value = res.data
}

// 输入框内容
const inputMessage = ref('')
// 加载状态
const loading = ref(false)
// 聊天记录容器引用
const chatHistoryRef = ref(null)

// 切换聊天
const switchChat = (chatId) => {
  currentChat.value = chatId
  getChatMessages(chatId)
}

// 创建新对话
const createNewChat = () => {
  const newId = chatType.value + uuidv4()
  chatList.value.push(newId)
  switchChat(newId)
}

// 发送消息处理
const handleSend = async () => {
  if (isStreaming.value) return
  if (!inputMessage.value.trim() || loading.value) return
  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: inputMessage.value.trim(),
  }
  // currentChat.messages.push(userMessage)
  currentChatMessages.value.push(userMessage)

  // 添加助手消息占位
  const assistantMessage = {
    role: 'assistant',
    content: '',
  }
  currentChatMessages.value.push(assistantMessage)
  isStreaming.value = true
  try {
    const params = {
      prompt: inputMessage.value.trim(),
      chatId: currentChat.value,
    }
    const response = await fetch(import.meta.env.VITE_APP_BASE_API + '/ai/knowledge/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + getToken(),
      },
      body: new URLSearchParams(params)
    });
    const reader = response.body.getReader();
    console.log('reader', reader)
    const decoder = new TextDecoder('utf-8')
    let accumulatedContent = ''  // 添加累积内容变量
    while (true) {
      try {
        const { value, done } = await reader.read()
        if (done) break
        // 累积新内容
        accumulatedContent += decoder.decode(value)
        await nextTick(() => {
          // 更新消息，使用累积的内容
          const updatedMessage = {
            ...assistantMessage,
            content: accumulatedContent  // 使用累积的内容
          }
          const lastIndex = currentChatMessages.value.length - 1
          currentChatMessages.value.splice(lastIndex, 1, updatedMessage)
        })
        await scrollToBottom()
      } catch (readError) {
        console.error('读取流错误:', readError)
        break
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    assistantMessage.content = '抱歉，发生了错误，请稍后重试。'
  } finally {
    isStreaming.value = false
    // 清空输入框并滚动到底部
    inputMessage.value = ''
    loading.value = false
    await scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatHistoryRef.value) {
    chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
  }
}

// 组件挂载后初始化
onMounted(() => {
  // 可以在这里添加初始化逻辑，比如加载历史消息等
  getChatList()
})
</script>

<style scoped>
.chat-layout {
  display: flex;
  height: calc(100vh - 84px);
  background-color: #f5f7fa;
}

.chat-sidebar {
  width: 250px;
  background-color: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  margin-bottom: 5px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.chat-item:hover {
  background-color: #f5f7fa;
}

.chat-item.active {
  background-color: #ecf5ff;
  color: #409eff;
}

.chat-item .el-icon {
  margin-right: 10px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-wrapper {
  margin-bottom: 20px;
}

.message-row {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.message-content {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 4px;
  word-break: break-word;
}

.user-message {
  flex-direction: row-reverse;
}

.user-message .message-content {
  background-color: #e5f2ff;
  margin-right: 8px;
}

.ai-message .message-content {
  background-color: #f4f4f5;
  margin-left: 8px;
}

.avatar {
  flex-shrink: 0;
}

.chat-input {
  padding: 20px;
  background-color: white;
  border-top: 1px solid #eee;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>